/**
 ********************************************************************
 * @author roocket
 * @file    file_sync.h
 * @version V0.0.0
 * @date    2024/3/22
 * @brief   This file is to indicate file sync functions. 
 * @attention Code file rules:
 * rule: file encoding use UTF8;
 * rule: max line length 120 characters;
 * rule: line separator \r\n;
 * rule: use clion auto code format tool.
 */

#include "file_synchronize.h"

int file_sync_copy_content(const char *old_file_name, const char *new_file_name, double *t)
{
    unsigned char ins[FILE_SYNC_BUFFER_LEN];
    int inl;
    FILE *in = NULL;
    FILE *out = NULL;
    int err = -1;
    clock_t st, et;

    if (!strcmp(old_file_name, new_file_name))
        goto fail_close;

    st = clock();

    in = fopen(old_file_name, "rb");
    if (NULL == in)
        goto fail_close;

    out = fopen(new_file_name, "wb");
    if (NULL == out)
        goto fail_close;

    while (!feof(in)) {
        inl = fread(ins, 1, FILE_SYNC_BUFFER_LEN, in);
        fwrite(ins, 1, inl, out);
        fflush(out);
    }

    /* clock the time */
    et = clock();
    *t = (double)(et - st) / CLOCKS_PER_SEC;

    err = 0;

fail_close:
    if (in)
        fclose(in);
    if (out)
        fclose(out);
    return err;
}
